<?php
class News_model extends CI_Model{
	function __construct(){
		parent::__construct();
	}
	
	function RowCount($search = null){
		if(is_null($search)){
			return $this->db->count_all('TB_NEWS');
		} else {
			if(!empty($search['Title'])){
				$this->db->like('Title', $search['Title'], 'both'); 
			}
			if(!empty($search['NewsID'])){
				$this->db->where('NewsID', $search['NewsID']); 
			}
			if(!empty($search['CategoryID'])){
				$this->db->where('CategoryID', $search['CategoryID']); 
			}
			return $this->db->count_all_results('TB_NEWS');
		}
	}
	
	function GetListForPaging($limit, $page, $search = null){
		$this->db->select('TB_NEWS.*, TB_ADMIN.UserName, TB_CATEGORY.CategoryName');
		if(!is_null($search)){
			if(!empty($search['Title'])){
				$this->db->like('Title', $search['Title'], 'both'); 
			}
			if(!empty($search['NewsID'])){
				$this->db->where('NewsID', $search['NewsID']); 
			}
			if(!empty($search['CategoryID'])){
				$this->db->where('CategoryID', $search['CategoryID']); 
			}
		}
		$this->db->join('TB_CATEGORY', 'TB_CATEGORY.CategoryID = TB_NEWS.CategoryID');
		$this->db->join('TB_ADMIN', 'TB_ADMIN.UserID = TB_NEWS.UserID');
		$this->db->limit($limit, $page);
		$query = $this->db->get('TB_NEWS');
		return $query->result();
	}
	
	function GetInfoByID($NewsID){
		$this->db->where('NewsID', $NewsID);
		$query = $this->db->get('TB_NEWS');
		$result = $query->result();
		if(empty($result)){
			return false;
		} else {
			return $result[0];
		}
	}
	
	function ChangeStatus($NewsID, $field){
		if(is_array($NewsID)){
			$this->db->where_in('NewsID', $NewsID);
		} else {
			$this->db->where('NewsID', $NewsID);
		}
		if($field == 'Disable'){
			return $this->db->update('TB_NEWS', array('Status', 0)); 
		} else {
			return $this->db->update('TB_NEWS', array('Status', 1)); 
		}
	}
	
	function InsertNews($arr){
		$data = array(	'Title' => $arr['Title']		,	'Description' => $arr['Description']	,	'Avatar' => $arr['Avatar'],
						'Content' => $arr['Content']	,	'Code' => $arr['Code']					,	'CategoryID' => $arr['CategoryID'],
						'UserID' => $arr['UserID']		,	'CreateDate' => date('Y-m-d H:i:s'));
		$this->db->set($data);
		return $this->db->insert('TB_NEWS');
	}
	
	function UpdateNews($arr){
		$data = array(	'Title' => $arr['Title']		,	'Description' => $arr['Description']	,	'Avatar' => $arr['Avatar'],
						'Content' => $arr['Content']	,	'Code' => $arr['Code']					,	'CategoryID' => $arr['CategoryID'],
						);
		$this->db->where('NewsID', $arr['NewsID']);
		return $this->db->update('TB_NEWS', $data);
	}
	
	function GetListCategory(){
		$query = $this->db->get('TB_CATEGORY');
		return $query->result();
	}
}
?>